<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { Search, CirclePlus } from '@element-plus/icons-vue';
import { Refresh } from '@element-plus/icons-vue';
import { SearchParams, TableItem, addFamilyMember, addHouseholder, findFamilyAllMember, findMember, findResidentRegistry, modifyMember, removeResidentRegistry } from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from '@/pinna';
const infoStore = useStore()
onMounted(() => {
  findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)
const familyId = ref('')
const activeNames = ref([1])
const familyAllUser: Ref<Partial<TableItem>[]> = ref([])
const searchFrom: Ref<Partial<SearchParams>> = ref({
  name: '',
  residentRegistryAddress: '',
  idNumber: ''
})

const reset = () => {
  searchFrom.value = {
    name: '',
    residentRegistryAddress: '',
    idNumber: ''
  }
  findData()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  findData()
}

const handleCurrentChange = (val: number) => {
  pageNo.value = val
  findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<TableItem[]>> = ref([])

const findData = async () => {
  await findMember({
    pageNo: toValue(pageNo),
    pageSize: toValue(pageSize),
    name: searchFrom.value.name,
    residentRegistryAddress: searchFrom.value.residentRegistryAddress,
    idNumber: searchFrom.value.idNumber,
  }).then((res: any) => {
    const { code, data, total: tableTotal } = res

    if (code === 200) {
      tableData.value = data
      total.value = tableTotal
      console.log(total);

    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

const findRoleInfo = async (id: string) => {
  await findResidentRegistry({ id }).then((res: any) => {
    const { data } = res
    data.sex = data.sex == 0 ? '男' : '女'
    addHsotForm.value = data
    dialogHostTitle.value = '查看详情'
    dialogHost.value = true
  })
}

const editRoleInfo = async (id: string) => {
  await findResidentRegistry({ id }).then((res: any) => {
    const { data } = res
    data.sex = data.sex == 0 ? '男' : '女'
    addHsotForm.value = data
    dialogHostTitle.value = '编辑信息'
    dialogHost.value = true
  })
}

const deleteRoleInfo = async (id: string) => {
  ElMessageBox.confirm(
    '是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await removeResidentRegistry({ id }).then((res: any) => {
        if (res.code == 200) {
          findData()
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
        }
      })
    })

}

const addHouseFamily = (id: string) => {
  familyId.value = id
  dialogHostTitle.value = '添加家庭成员'
  resetDialogHostFrom()
  dialogHost.value = true
}

const findHouseFamily = async (familyId: string) => {
  await findFamilyAllMember({ familyId }).then((res: any) => {
    const { code, data } = res
    if (code == 200) {
      familyAllUser.value = data
      dialogFamily.value = true
    }
  })
}

// 添加户主弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加户主')
const formLabelWidth = '100px'
const addHsotForm: Ref<Partial<TableItem>> = ref({
  name: "",
  sex: '',
  age: '',
  idNumber: "",
  phone: "",
  resideAddress: "",
  residentRegistryAddress: "",
  profession: "",
  relationshipWithHouseholder: "",
  familyId: ""
})

const resetDialogHostFrom = () => {
  addHsotForm.value = {
    name: "",
    sex: '',
    age: '',
    idNumber: "",
    phone: "",
    resideAddress: "",
    residentRegistryAddress: "",
    profession: "",
    relationshipWithHouseholder: "",
    familyId: ""
  }
}

const addHostDialog = () => {
  resetDialogHostFrom()
  dialogHostTitle.value = '添加户主'
  dialogHost.value = true
}
const addHostSubmit = async () => {
  if (dialogHostTitle.value == '查看详情') return dialogHost.value = false
  if (dialogHostTitle.value == '添加户主') {
    await addHouseholder(unref(addHsotForm)).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '新增户主成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '编辑信息') {
    const isSelectSex = addHsotForm.value.sex == '0' || addHsotForm.value.sex == '1'
    addHsotForm.value.sex = !isSelectSex ? addHsotForm.value.sex == '男' ? 0 : 1 : addHsotForm.value.sex
    await modifyMember(unref(addHsotForm)).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '编辑成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '添加家庭成员') {
    const isSelectSex = addHsotForm.value.sex == '0' || addHsotForm.value.sex == '1'
    addHsotForm.value.sex = !isSelectSex ? addHsotForm.value.sex == '男' ? 0 : 1 : addHsotForm.value.sex
    addHsotForm.value.familyId = familyId.value
    await addFamilyMember(unref(addHsotForm)).then((res: any) => {
      const { code } = res
      if (code === 200) {
        dialogHost.value = false
        findData()
        resetDialogHostFrom()
        ElMessage({
          message: '编辑成功',
          type: 'success'
        })
      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  }

}

// 查看家庭成员弹窗
let dialogFamily = ref(false)

const isReadonlyHandler = computed(() => {
  return dialogHostTitle.value !== '查看详情'
})
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span><strong>户籍管理</strong></span>
      </div>
    </template>
    <div class="query-input">
      <el-input v-model="searchFrom.name" placeholder="请输入姓名" />
      <el-input v-model="searchFrom.idNumber" placeholder="请输入身份证号" />
      <el-input v-model="searchFrom.residentRegistryAddress" placeholder="户籍地址" />
      <el-button type="primary" @click="findData()">
        <el-icon>
          <Search />
        </el-icon>
        查询
      </el-button>
      <el-button type="danger" @click="reset()">
        <el-icon>
          <Refresh />
        </el-icon>
        重置
      </el-button>
    </div>

  </el-card>

  <el-card>
    <div>
      <el-button key="'添加户主'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
        class="addUser">添加户主</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.sex == 0 ? '男' : '女' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="householder" label="户主">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.householder ? '是' : '否' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="profession" label="职业" />
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="idNumber" label="身份证号码" />
      <el-table-column prop="relationshipWithHouseholder" label="与户主的关系">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px">{{ scope.row.relationshipWithHouseholder ?? '户主本人' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="resideAddress" label="居住地址" />
      <el-table-column prop="residentRegistryAddress" label="户籍地址" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-space wrap>


            <el-button v-if="scope.row.householder" type="primary" size="small" color="#626aef" plain
              @click="addHouseFamily(scope.row.familyId)">添加家庭成员</el-button>
            <el-button type="primary" v-if="infoStore.$state.info.role == 'admin'" plain size="small" @click="findHouseFamily(scope.row.familyId)">查看家庭成员</el-button>
            <el-button type="primary" size="small" plain @click="findRoleInfo(scope.row.id)">查看</el-button>
            <el-button type="primary" v-if="infoStore.$state.info.role == 'admin'" size="small" plain @click="editRoleInfo(scope.row.id)">编辑</el-button>
            <el-button type="danger" v-if="infoStore.$state.info.role == 'admin'" size="small" color="red" plain @click="deleteRoleInfo(scope.row.id)">删除</el-button>
          </el-space>
        </template>
      </el-table-column>

    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-card>
  <!-- 添加户主弹框 -->
  <el-dialog v-model="dialogHost" :title="dialogHostTitle">
    <el-form :model="addHsotForm">
      <el-form-item label="姓名:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.name" autocomplete="off" :disabled="!isReadonlyHandler" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别:" :label-width="formLabelWidth" required>
        <el-select v-model="addHsotForm.sex" placeholder="请选择性别" :disabled="!isReadonlyHandler">
          <el-option label="男" value="0" />
          <el-option label="女" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="年龄:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.age" autocomplete="off" placeholder="请输入年龄" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item v-if="!addHsotForm.householder" label="与户主关系:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.relationshipWithHouseholder" autocomplete="off" placeholder="请输入与户主关系"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="身份证号码:" :label-width="formLabelWidth" required>
        <el-input v-model="addHsotForm.idNumber" autocomplete="off" placeholder="请输入身份证号码"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="手机号码:" :label-width="formLabelWidth" type="number" required>
        <el-input v-model="addHsotForm.phone" autocomplete="off" placeholder="请输入手机号码" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="居住地址:" :label-width="formLabelWidth" required>
        <el-input v-model="addHsotForm.resideAddress" autocomplete="off" :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea" placeholder="请输入居住地址" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="户籍地址:" :label-width="formLabelWidth" required>
        <el-input v-model="addHsotForm.residentRegistryAddress" autocomplete="off" :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea" placeholder="请输入户籍地址" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="职业:" :label-width="formLabelWidth">
        <el-input v-model="addHsotForm.profession" autocomplete="off" placeholder="请输入职业"
          :disabled="!isReadonlyHandler" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogHost = false">取消</el-button>
        <el-button type="primary" v-if="isReadonlyHandler" @click="addHostSubmit()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 家庭成员弹框 -->
  <el-dialog v-model="dialogFamily" title="家庭全部成员查看">
    <el-collapse v-model="activeNames" style="max-height: 400px;
    overflow: auto;">
      <div v-for="(item, index) in familyAllUser" :key="item.id">
        <el-collapse-item :title="item.relationshipWithHouseholder || '户主'" :name="index + 1">
          <el-form :model="item">
            <el-form-item label="姓名:" :label-width="formLabelWidth" clearable required>
              <el-input v-model="item.name" autocomplete="off" placeholder="请输入姓名" disabled />
            </el-form-item>
            <el-form-item label="性别:" :label-width="formLabelWidth" required>
              <el-select v-model="item.sex" placeholder="请选择性别" disabled>
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄:" :label-width="formLabelWidth" clearable required>
              <el-input v-model="item.age" autocomplete="off" placeholder="请输入年龄" disabled />
            </el-form-item>
            <el-form-item v-if="familyId" label="与户主关系:" :label-width="formLabelWidth" clearable required>
              <el-input v-model="item.relationshipWithHouseholder" autocomplete="off" placeholder="请输入与户主关系" disabled />
            </el-form-item>
            <el-form-item label="身份证号码:" :label-width="formLabelWidth" required>
              <el-input v-model="item.idNumber" autocomplete="off" placeholder="请输入身份证号码" disabled />
            </el-form-item>
            <el-form-item label="手机号码:" :label-width="formLabelWidth" type="number" required>
              <el-input v-model="item.phone" autocomplete="off" placeholder="请输入手机号码" disabled />
            </el-form-item>
            <el-form-item label="居住地址:" :label-width="formLabelWidth" required>
              <el-input v-model="item.resideAddress" autocomplete="off" :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea" placeholder="请输入居住地址" disabled />
            </el-form-item>
            <el-form-item label="户籍地址:" :label-width="formLabelWidth" required>
              <el-input v-model="item.residentRegistryAddress" autocomplete="off" :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea" placeholder="请输入户籍地址" disabled />
            </el-form-item>
            <el-form-item label="职业:" :label-width="formLabelWidth">
              <el-input v-model="item.profession" autocomplete="off" placeholder="请输入职业" disabled />
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </div>
    </el-collapse>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFamily = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input {
  margin-right: 5px;
  width: 400px;
}

.query-input {
  display: flex;
  gap: 10;
}

.el-card {
  margin-bottom: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.addUser {
  float: right;
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
  width: 400px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}</style>